package com.baigao.springboot.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baigao.springboot.util.ExportFileUtils;
import com.baigao.springboot.util.FileUtil;

@Controller
public class UploadOrDowloadFileController {
	private static final String UPLOAD_FILE = "uplaod/";//上传文件路径
    @Value("${file.path}")
    private String filePath;

  /**
   * 上传文件
   * @param request
   * @param response
   * @param file 上传的文件，支持多文件
   * @throws Exception
   */
  @ResponseBody
  @RequestMapping("/upload2")
  public Map<String, Object> insert(HttpServletRequest request,HttpServletResponse response
          ,@RequestParam("file") MultipartFile[] file) throws Exception{
  	
  	Map<String, Object> map = new HashMap<String, Object>();
  	
      if(file!=null&&file.length>0){
          //组合image名称，“;隔开”
          List<String> fileName =new ArrayList<String>();
          try {
              for (int i = 0; i < file.length; i++) {
                  if (!file[i].isEmpty()) {

                      //上传文件，随机名称，";"分号隔开
                      fileName.add(uploadImage2SaveFileFromInputStream(request, filePath, file[i], true));
                  }
              }

              //上传成功
              if(fileName!=null&&fileName.size()>0){
                  System.out.println("上传成功！"+fileName.toString());
                  
                  map.put("fileName", fileName);
                  map.put("msg", "上传成功！");
                  return map;
              }else {
                  System.out.println("上传失败！文件格式错误！");
                  map.put("fileName", fileName);
                  map.put("msg", "上传失败！文件格式错误！");
                  return map;
              }
          } catch (Exception e) {
              e.printStackTrace();
              System.out.println("上传出现异常！异常出现在：class.UploadController.insert()");
              map.put("fileName", fileName);
              map.put("msg", "上传出现异常！异常出现在");
              return map;
          }
      }else {
      	System.out.println("没有检测到文件！");
      	map.put("fileName", "");
          map.put("msg", "没有检测到文件！");
          return map;
      }
  }
  
    private String uploadImage2SaveFileFromInputStream(HttpServletRequest request, String filePath2,
		MultipartFile file, boolean b) throws IOException {


    	String fileType = file.getContentType();
    	
		if(fileType.toLowerCase().indexOf("image")<0){
			System.out.println("该文件不是图片类型！");
			return null;
		}
		
		// 获得文件名：
		String filename = file.getOriginalFilename();
		String[] temp1 = filename.split("\\.");
		String extenName = temp1[temp1.length - 1];
		StringBuffer fileNameBuffer = new StringBuffer();
		fileNameBuffer.append(UUID.randomUUID()).append(".").append(extenName);
		
		InputStream input = file.getInputStream();
		
		//获取跟目录
		File path2=new File(ResourceUtils.getURL("classpath:").getPath());
		if(!path2.exists()){
			path2=new File("");
		}
		//如果上传目录为/static/upload/,则可以如下获取
		File upload = new File(path2.getAbsolutePath(),"static/"+UPLOAD_FILE);
		if(!upload.exists()){
			 upload.mkdirs();
			 System.out.println(upload.getAbsolutePath());
			//在开发测试模式时，得到地址为：{项目跟目录}/target/static/upload/
			 //在打成jar正式发布时，得到的地址为:{发布jar包目录}/static/upload/

		}
		
		
		FileUtil.SaveFileFromInputStream(input, upload.toString(),fileNameBuffer.toString());
		return UPLOAD_FILE + fileNameBuffer;
}

	/**
     * 下载文件
     * @param request
     * @param response
     * @param file 上传的文件，支持多文件
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/dowloadImgByName")
    public void dowloadImgByName(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	String imgName = request.getParameter("imgName");
    	
    	if("" == imgName || null == imgName) {
    		System.out.println("文件名不能为空！");
    	}
//    	String actionPath = request.getSession().getServletContext().getRealPath("");
//		String path = actionPath +File.separator+EXPORT_TEMPLET;
		File exportPath = new File("static/"+UPLOAD_FILE);
		
    	ExportFileUtils.downloadFile(response, request, exportPath.toString(), imgName);
    }
    
    
    /**
     * <p>
     * Description:[删除图片]
     * </p>
     * 
     * Created by [Administrator] [2019年1月9日]
     * Midified by [修改人] [修改时间]
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/deletImgByName")
    public Map<String, Object> deletImgByName(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	String imgName = request.getParameter("imgName");
    	
    	if("" == imgName || null == imgName) {
    		System.out.println("文件名不能为空！");
    		resultMap.put("STATUS", "-1");
    		resultMap.put("MSG", "文件名不能为空！");
    		resultMap.put("imgName", imgName);
    		return resultMap;
    	}
    	//获取跟目录
		File path2=new File(ResourceUtils.getURL("classpath:").getPath());
		if(!path2.exists()){
			path2=new File("");
		}
		//如果上传目录为/static/upload/,则可以如下获取
		File deleteFile  = new File(path2.getAbsolutePath(),"static/"+UPLOAD_FILE+imgName);
		
    	boolean flage = false;
    	
		if (deleteFile.isFile() && deleteFile.exists()) {
			flage = deleteFile.delete();
		}
		
		resultMap.put("STATUS", flage ? "1":"0");
		resultMap.put("MSG", flage ? "删除成功":"删除图片失败！");
		resultMap.put("imgName", imgName);
    	return resultMap;
    }
    
    /**
	 * <p>
	 * Description:[删除图片]
	 * </p>
	 * 
	 * Created by [lqw] [2019年01月10日]
	 * Midified by [修改人] [修改时间]
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteImg", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteImg(HttpServletRequest request) {
		String filepath = request.getParameter("filepath");
		String actionPath = request.getSession().getServletContext().getRealPath("");
		Map<String, Object> rm = new HashMap<String, Object>();
		String msg = FileUtil.deleteFiles(actionPath,filepath);
		boolean flage = false;
		flage = "".equals(msg) ? true:false;
		
		rm.put("STATUS", flage ? "1":"0");
		rm.put("MSG", flage ? "删除成功":"删除图片失败！");
		rm.put("imgName", filepath);
		return rm;
	}
    
    /**
     * <p>
     * Description:[查询图片]
     * </p>
     * 
     * Created by [Administrator] [2019年1月9日]
     * Midified by [修改人] [修改时间]
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/queryImgs")
    public Map<String, Object> queryImgs(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	String[] suffixs = new String[] {"jpg","gif", "png","bmp"};
    	List<String> findFiles = new ArrayList<String>();;
    	List<String> findFilePaths = new ArrayList<String>();
		
		//获取跟目录
		File path2=new File(ResourceUtils.getURL("classpath:").getPath());
		if(!path2.exists()){
			path2=new File("");
		}
		//如果上传目录为/static/upload/,则可以如下获取
		File upload = new File(path2.getAbsolutePath(),"static/"+UPLOAD_FILE);
		if(!upload.exists()){
			 upload.mkdirs();
			 System.out.println(upload.getAbsolutePath());
			//在开发测试模式时，得到地址为：{项目跟目录}/target/static/upload/
			 //在打成jar正式发布时，得到的地址为:{发布jar包目录}/static/upload/

		}
				
    	findFiles = FileUtil.findFiles(upload.toString(), suffixs);
    	
    	if(null != findFiles && findFiles.size()>0) {
    		for (int i = 0; i < findFiles.size(); i++) {
    			findFilePaths.add("../"+UPLOAD_FILE);
			}
    	}
    	resultMap.put("STATUS", findFiles.size() >0 ? "1":"0");
    	resultMap.put("MSG", findFiles.size() >0 ? "成功":"查询图片失败！");
    	resultMap.put("findFiles", findFiles);
    	resultMap.put("findFilePaths", findFilePaths);
    	return resultMap;
    }
    
    
    /**
     * 上传图片
     *  原名称
     * @param request 请求
     * @param path_deposit 存放位置(路径)
     * @param file 文件
     * @param isRandomName 是否随机名称
     * @return 完整文件路径
     */
    public static String uploadImage(HttpServletRequest request,String path_deposit,MultipartFile file,boolean isRandomName) {
        //上传
        try {
            String[] typeImg={"gif","png","jpg"};
 
            if(file!=null){
                String origName=file.getOriginalFilename();// 文件原名称
                System.out.println("上传的文件原名称:"+origName);
                // 判断文件类型
                String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
                if (type!=null) {
                    boolean booIsType=false;
                    for (int i = 0; i < typeImg.length; i++) {
                        if (typeImg[i].equals(type.toLowerCase())) {
                            booIsType=true;
                        }
                    }
                    //类型正确
                    if (booIsType) {
                        //存放图片文件的路径
                        String path=path_deposit;
                        //组合名称
                        String fileSrc=""; 
                        //是否随机名称
                        if(isRandomName){
                            origName=UUID.randomUUID().toString()+origName.substring(origName.lastIndexOf("."));
                        }
                        //判断是否存在目录
                        File targetFile=new File(path);
                        if(!targetFile.exists()){
                            targetFile.mkdirs();//创建目录
                        }
                     // 文件保存路径  
                        String savePath = path + origName;  
                        // 转存文件  上传
                        file.transferTo(new File(savePath)); 
                        //完整路径
                        fileSrc=savePath;
                        System.out.println("图片上传成功:"+fileSrc);
                        return fileSrc;
                    }
                }
            }
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
